package com.zlyx.easy.redis.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.zlyx.easy.core.annotations.SpringBean;

@SpringBean(todo = { "Redis工具类" })
public class RedisUtils {

	public final static String DEFAULT_CHANNEL = "easy-redis-channel";

	private static StringRedisTemplate stringRedisTemplate;

	@Autowired(required = false)
	public RedisUtils(StringRedisTemplate stringRedisTemplate) {
		RedisUtils.stringRedisTemplate = stringRedisTemplate;
	}

	/**
	 * 获取StringRedisTemplate
	 * 
	 * @return
	 */
	public static StringRedisTemplate getRedisTemplate() {
		return stringRedisTemplate;
	}

	/**
	 * 获取redis连接工厂
	 * 
	 * @return
	 */
	public static RedisConnectionFactory getConnectionFactory() {
		return getRedisTemplate().getConnectionFactory();
	}

	/**
	 * 删除某个key
	 * 
	 * @param key
	 * @return
	 */
	public static Boolean delete(String key) {
		return getRedisTemplate().delete(key);
	}

	/**
	 * 添加hash键值对
	 * 
	 * @param key
	 * @param value
	 */
	public static void set(String key, String value) {
		getRedisTemplate().opsForValue().set(key, value);
	}

	/**
	 * 根据key得到hash值
	 * 
	 * @param key
	 * @param value
	 */
	public static String get(String key) {
		return getRedisTemplate().opsForValue().get(key);
	}

	/**
	 * list队列中右侧取出
	 * 
	 * @param key
	 * @return
	 */
	public static ListOperations<String, String> opsForList() {
		return getRedisTemplate().opsForList();
	}

	/**
	 * 推送消息(需要配合MessageListener接口来接受数据,需要手动转换数据格式)
	 * 
	 * @param channel
	 * @param message
	 */
	public static void publish(String channel, String message) {
		getRedisTemplate().convertAndSend(channel, message);
	}

	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T deserialize(byte[] bytes) {
		return (T) getRedisTemplate().getValueSerializer().deserialize(bytes);
	}
}
